package com.cy.store.service.impl;

import com.cy.store.entity.User;
import com.cy.store.mapper.UserMapper;
import com.cy.store.service.IUserService;
import com.cy.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

/**
 * 用户模块业务层的实现类
 */
@Service //将当前对象交给spring管理，创建对象并维护
public class UserServiceImpl implements IUserService {
    @Autowired(required = false)
    private UserMapper userMapper;

    @Override
    public void reg(User user) {
        //判断username是否在数据库中已经存在了
        User byUsername = userMapper.findByUsername(user.getUsername());
        if (byUsername != null) {
            //不为空 则抛出异常
            throw new UsernameDuplicatedException("用户名已经被占用!");
        }


        //密码加密处理实现：md5密码
        // 盐值+ 密码 + 盐值  ----------md5算法加密，连续加载三次
        //盐值：随机字符串

        //获取密码
        String oldPassword = user.getPassword();
        //获取盐值（随机生成一个盐值）   全部大写了
        String salt = UUID.randomUUID().toString().toUpperCase();
        //在本类加密方法中实现
        String md5Password = getMD5Password(oldPassword, salt);
        //将密码放回user中
        user.setPassword(md5Password);
        //补全盐值记录
        user.setSalt(salt);

        //补全数据，is_delete设置为0
        user.setIsDelete(0);
        //补全数据：4个日志字段信息
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);


        //执行注册业务功能实现  当返回值为1的时候，则代表插入成功
        int i = userMapper.insertUser(user);
        if (i != 1) {
            throw new InsertEception("在执行过程中产生了为止的异常！");
        }
    }

    /**
     * 登录功能
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public User login(String username, String password) {
        User user = userMapper.findByUsername(username);
        //判断用户名称是否存在
        if (user == null) {
            throw new UserNotFoundException("没有找到该用户");
        }
        //判断密码是否正确
        //1.获取数据库中加密后的密码
        String rightPassword = user.getPassword();
        //2.和用户传递过来的密码值作比较
        //2.1将用户传递过来的密码使用md5算法进行加密后比较
        String salt = user.getSalt();
        String md5Password = getMD5Password(password, salt);

        if (!md5Password.equals(rightPassword)) {
            throw new PasswordNotMatchException("密码错误");
        }
        if (user.getIsDelete() == 1) {
            throw new UserNotFoundException("用户数据不存在");
        }

        //最后只返回部分需要展示的数据
        User reUser = new User();
        reUser.setUsername(user.getUsername());
        reUser.setUid(user.getUid());
        reUser.setAvatar(user.getAvatar());

        return reUser;

    }

    /**
     * 修改用户密码
     *
     * @param uid
     * @param username    用户名
     * @param oldPassword 老密码
     * @param newPassword 新密码
     */
    @Override
    public void changePassword(Integer uid, String username, String oldPassword, String newPassword) {
        User byUid = userMapper.findByUid(uid);
        if (uid == null) {
            throw new UpdateException("查无此人或其他错误");
        }
        String md5Password = getMD5Password(oldPassword, byUid.getSalt());
        if (!md5Password.equals(byUid.getPassword())) {
            throw new UpdateException("原密码输入错误");
        }
        Integer integer = userMapper.updatePasswordByUid(uid, md5Password, username, new Date());
        System.out.println(integer);

        if (integer != 1) {
            throw new UpdateException("更新发生为止错误");
        }

    }

    /**
     * 根据uid查询用户数据
     *
     * @param uid
     * @return
     */
    @Override
    public User getByUid(Integer uid) {
        User byUid = userMapper.findByUid(uid);
        if (byUid == null || byUid.getIsDelete() == 1) {
            throw new UserNotFoundException("用户数据不存在");
        }
        User user = new User();
        user.setUsername(byUid.getUsername());
        user.setPhone(byUid.getPhone());
        user.setEmail(byUid.getEmail());
        user.setGender(byUid.getGender());

        return user;
    }

    /**
     * 更新用户的数据操作
     *
     * @param uid
     * @param username
     * @param user
     */
    @Override
    public void changeInfo(Integer uid, String username, User user) {
        User byUid = userMapper.findByUid(uid);
        if (byUid == null || byUid.getIsDelete() == 1) {
            throw new UserNotFoundException("用户数据不存在");
        }
        user.setUid(uid);
        //user.setUsername(username);
        user.setModifiedUser(username);
        user.setModifiedTime(new Date());

        Integer integer = userMapper.updateInfoUid(user);
        if (integer != 1){
            throw new UpdateException("更新时产生未知异常");
        }


    }

    @Override
    public void changeAvatar(Integer uid, String avatar, String username) {
        User byUid = userMapper.findByUid(uid);
        if (byUid == null){
            throw new UserNotFoundException("用户不存在");
        }

        Integer integer = userMapper.updateAvatarByUid(uid, avatar, username, new Date());

        if (integer != 1){
            throw new UpdateException("更新出现异常");
        }

    }


    /**
     * 定义一个md5算法加密处理
     *
     * @param password
     * @param salt
     * @return
     */
    private String getMD5Password(String password, String salt) {
        //md5加密算法及其调用(进行三次)    并转化成全部大写
        for (int i = 0; i < 3; i++) {
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        return password;//返回加密之后的算法
    }
}
